package com.modular.handler;

import cn.hutool.core.io.IoUtil;
import com.modular.constant.BaseCodeDesc;
import com.modular.json.JackJsonUtil;
import com.modular.result.RspMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationHandler implements AccessDeniedHandler {
    private static Logger logger = LoggerFactory.getLogger(AuthenticationHandler.class);


    public AuthenticationHandler() {
    }

    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) {
        response.setCharacterEncoding("utf-8");
        response.setStatus(403);
        response.setContentType("application/json;charset=utf-8");
        RspMessage<Object> rspMessage = RspMessage.result(BaseCodeDesc.FORBIDDEN);

        try {
            IoUtil.writeUtf8(response.getOutputStream(), true, new Object[]{JackJsonUtil.toJsonIgnoreNull(rspMessage)});
        } catch (IOException var6) {
            logger.error("使用IoUtil.writeUtf8向前端输出信息时输出流异常: {}", var6.getMessage(), var6);
        }

    }
}
